using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour, ISaveManager
{
    public static GameManager instance; // 单例模式实例

    private Transform player;

    [SerializeField] private GameObject checkeParent; // 检查点父结点
    [SerializeField] private CheckPoint[] checkPoints; // 检查点数组
    public string closestCheckpointId; // 最近的检查点ID

    [Header("Lost currency")]
    [SerializeField] private GameObject lostCurrenyPrefab; // 丢失货币的预制体
    public int lostCurrencyAmount; // 丢失的货币数量
    [SerializeField] private float lostCurrencyX; // 丢失货币的X坐标
    [SerializeField] private float lostCurrencyY; // 丢失货币的Y坐标

    private void Awake()
    {
        if (instance != null)
        {
            Destroy(instance); // 如果实例已存在，销毁当前实例
        }
        else
        {
            instance = this; // 否则，将当前实例赋值给instance
        }
        // checkPoints = FindObjectsOfType<CheckPoint>(); // 查找所有CheckPoint对象1
        checkPoints = checkeParent.GetComponentsInChildren<CheckPoint>(); // 查找所有CheckPoint对象2
    }

    private void Start()
    {
        player = PlayerManager.instance.player.transform; // 获取玩家的Transform
    }

    public void RestartScene()
    {
        SaveManager.instance.SaveGame(); // 死亡后点击再次游戏时保存游戏
        Scene scene = SceneManager.GetActiveScene(); // 获取当前场景
        SceneManager.LoadScene(scene.name); // 重新加载当前场景
    }

    // 加载数据
    public void LoadData(GameData _data)
    {
        // Invoke("LoadClosestCheckpoint", .1f); // 延时获取检查点位置
        StartCoroutine(LoadWithDelay(_data)); // 启动协程延时加载数据
    }

    // 保存数据接口
    public void SaveData(ref GameData _data)
    {
        if (FindClosestCheckploint() != null)
            _data.closestCheckpointId = FindClosestCheckploint().checkpointId; // 找到最近的检查点ID
        _data.checkpoints.Clear(); // 清空检查点数据
        foreach (CheckPoint checkPoint in checkPoints)
        {
            _data.checkpoints.Add(checkPoint.checkpointId, checkPoint.activated); // 保存检查点数据
        }

        _data.lostCurrencyAmount = lostCurrencyAmount; // 保存丢失的货币数量
        _data.lostCurrencyX = player.position.x; // 保存丢失货币的X坐标
        _data.lostCurrencyY = player.position.y; // 保存丢失货币的Y坐标
    }

    private IEnumerator LoadWithDelay(GameData _data)
    {
        yield return new WaitForSeconds(.1f); // 延时0.1秒
        LoadLostCurrency(_data); // 加载丢失的货币
        LoadClosestCheckpoint(_data); // 加载最近的检查点
        LoadCheckPoint(_data); // 加载检查点数据
    }

    private void LoadLostCurrency(GameData _data)
    {
        lostCurrencyAmount = _data.lostCurrencyAmount; // 加载丢失的货币数量
        lostCurrencyX = _data.lostCurrencyX; // 加载丢失货币的X坐标
        lostCurrencyY = _data.lostCurrencyY; // 加载丢失货币的Y坐标
        if (lostCurrencyAmount > 0)
        {
            GameObject newLostCurrency = Instantiate(lostCurrenyPrefab, new Vector2(lostCurrencyX, lostCurrencyY), Quaternion.identity); // 实例化丢失货币的预制体
            newLostCurrency.GetComponent<LostCurrency>().currency = lostCurrencyAmount; // 设置丢失货币的数量
        }
        lostCurrencyAmount = 0; // 重置丢失货币数量
    }

    // 设置玩家出生点位置
    private void LoadClosestCheckpoint(GameData _data)
    {
        if (_data == null || _data.closestCheckpointId == null) return;
        closestCheckpointId = _data.closestCheckpointId; // 加载最近检查点ID
        foreach (CheckPoint checkPoint in checkPoints)
        {
            if (closestCheckpointId == checkPoint.checkpointId)
            {
                player.position = checkPoint.transform.position; // 设置玩家位置为最近检查点位置
            }
        }
    }

    // 设置检查点是否激活
    private void LoadCheckPoint(GameData _data)
    {
        foreach (KeyValuePair<string, bool> pair in _data.checkpoints)
        {
            foreach (CheckPoint checkPoint in checkPoints)
            {
                if (checkPoint.checkpointId == pair.Key && pair.Value == true)
                {
                    checkPoint.ActivateCheckpoint(); // 激活检查点
                    break;
                }
            }
        }
    }

    // 寻找最近的检查点
    private CheckPoint FindClosestCheckploint()
    {
        float closestDistance = Mathf.Infinity; // 初始化最近距离为无穷大
        CheckPoint closestCheckpoint = null; // 最近的检查点
        foreach (CheckPoint checkPoint in checkPoints)
        {
            float distanceToCheckpoint = Vector2.Distance(player.position, checkPoint.transform.position); // 计算玩家到检查点的距离
            if (distanceToCheckpoint < closestDistance && checkPoint.activated)
            {
                closestDistance = distanceToCheckpoint; // 更新最近距离
                closestCheckpoint = checkPoint; // 更新最近的检查点
            }
        }
        return closestCheckpoint; // 返回最近的检查点
    }

    public void PauseGame(bool _pause)
    {
        if (_pause)
        {
            Time.timeScale = 0;
        }else{
            Time.timeScale = 1;
        }
    }



}